package com.black.utils.network.transmit.tcp;

import com.black.utils.commons.pool.PoolProperties;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;

/**
 * 标准socket客户端
 *
 * @author ylx
 */
@Slf4j
@NoArgsConstructor
public class TCPClient {
    private String host;
    private int port;
    private Socket socket;
    private PrintWriter writer;
    private BufferedReader reader;

    public TCPClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public TCPClient(PoolProperties tcpProperties) throws IOException {
        this.host = tcpProperties.getIp();
        this.port = tcpProperties.getPort();
        connect();
    }

    // 连接到服务器
    public void connect() throws IOException {
        log.info("TCPClient: connect to server: {}:{}", host, port);
        socket = new Socket(host, port);
        writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }

    public boolean isAvailable() {
        return socket != null && !socket.isClosed();
    }

    public boolean isConnected() {
        return socket.isConnected() && writer != null && reader != null;
    }

    public void reConnect() {
        try {
            close();
            connect();
        } catch (IOException e) {
            log.error("TCPClient: reconnect error: {}", e.getMessage());
        }
    }

    // 发送消息到服务器
    public boolean send(String message) {
        try {
            log.info("TCPClient: send message: {}", message);
            if (!isConnected()) {
                log.error("TCPClient: send message error: socket is not connected");
                return false;
            }
            if (writer == null) {
                connect();
            }
            writer.println(message);
            String response = response();
            if (response == null) {
                log.error("TCPClient: send message error: response is null");
                return false;
            }
            log.info("TCPClient: response message: {}", response);
            return true;
        } catch (IOException e) {
            log.error("TCPClient: send message error: {}", e.getMessage());
        }
        return false;
    }

    // 接收服务器的响应
    public String response() throws IOException {
        return reader != null ? reader.readLine() : null;
    }

    public void close() {
        try {
            if (socket != null) {
                socket.close();
            }
            if (writer != null) {
                writer.close();
            }
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            log.error("TCPClient: close error: {}", e.getMessage());
        }
    }
}
